package com.java.test.java8.stream.reduce;

/**
 *
 * @author liubin
 *
 * @date 2017年10月26日上午11:44:48
 */

import java.util.Arrays;
import java.util.List;

public class LambdaMapReduce {
    private static List<User> users = Arrays.asList(new User(1, "张三", 12, User.Sex.MALE),
            new User(2, "李四", 21, User.Sex.FEMALE), new User(3, "王五", 32, User.Sex.MALE),
            new User(4, "赵六", 32, User.Sex.FEMALE));

    public static void main(String[] args) {
        reduceAvg();
        reduceSum();
    }

    // 注意，reduce操作每处理一个元素总是创建一个新值，
    // Stream.reduce适用于返回单个结果值的情况
    // 获取所有用户的平均年龄
    private static void reduceAvg() {
        // mapToInt的pipeline后面可以是average,max,min,count,sum
        double avg = users.parallelStream().mapToInt(User::getAge).average().getAsDouble();

        System.out.println("reduceAvg User Age: " + avg);
    }

    // 获取所有用户的年龄总和
    private static void reduceSum() {
        double sum = users.parallelStream().mapToInt(User::getAge).reduce(0, (x, y) -> x + y); // 可以简写为.sum()

        System.out.println("reduceSum User Age: " + sum);
    }
}
